import 'dart:async';


import 'package:chatbot/main.dart';
import 'package:chatbot/manager/dio_manager.dart';
import 'package:chatbot/manager/store_manager.dart';
import 'package:chatbot/utils/colors.dart';
import 'package:chatbot/utils/share_preference.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keychain/flutter_keychain.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:platform/platform.dart';
import 'package:uuid/uuid.dart';

class SplashPage extends StatefulWidget {
  SplashPage();

  @override
  _SplashState createState() => _SplashState();
}

class _SplashState extends State<SplashPage> {
  bool isInit = false;
  static const int TIMEOUT = 2 * 1000, MINI_TIME = 10;

  _SplashState();

  @override
  void initState() {
    super.initState();
    init();
    Timer.periodic(Duration(milliseconds: 10), (Timer timer) {
      if ((isInit && timer.tick * 10 > MINI_TIME) ||
          timer.tick * 10 >= TIMEOUT) {
        timer.cancel();

        Navigator.pushReplacement(context, CupertinoPageRoute(builder: (BuildContext context){
          return const MyHomePage();
        }
        ));

      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ChatColors.commonDarkColor,
      body: Center(
        child: CupertinoActivityIndicator(
            radius: 10.0, color: ChatColors.primaryColor),
      ),
    );
  }

  void init() async {
    DioManager.instance;
    await LocalStorage.init();
    if (StoreManager.getUUID() == null) {
      var savedUUID = await FlutterKeychain.get(key: "uuid");

      if (savedUUID == null) {
        String uuid = const Uuid().v1();
        StoreManager.putUUID(uuid);
        await FlutterKeychain.put(key: "uuid", value: uuid);
      } else {
        StoreManager.putUUID(savedUUID);
      }
    }
    if (StoreManager.getUID() == null) {
      var savedUid = await FlutterKeychain.get(key: "uidV3");

      if (savedUid == null) {
        String uid = "${DateTime.now().millisecondsSinceEpoch~/1000}";
        StoreManager.putUID(uid);
        await FlutterKeychain.put(key: "uidV3", value: uid);
      } else {
        StoreManager.putUID(savedUid);
      }
    }
    isInit = true;
  }


}
